package com.atguigu.tingshu.album.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.unit.DataUnit;
import cn.hutool.core.util.IdUtil;
import com.atguigu.tingshu.album.config.MinioConstantProperties;
import com.atguigu.tingshu.album.service.FileUploadService;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.UploadObjectArgs;
import io.minio.errors.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * @author ajin
 * @create 2024-09-29 21:15
 */
@Slf4j
@RequiredArgsConstructor
@Service
public class FileUploadServiceImpl implements FileUploadService {

    private final MinioClient minioClient;

    private final MinioConstantProperties properties;
    /**
     * 图片文件上传
     * @return
     */
    public String uploadImage(MultipartFile file) {
        try {
            //1.判断文件是否为图片
            BufferedImage image = ImageIO.read(file.getInputStream());
            if (image == null){
                throw new RuntimeException("上传文件不是图片");
            }
            //2.上传文件 /2024-9-29/UUid.jgp
            String folder = DateUtil.today();
            String fileName = IdUtil.randomUUID();
            //2.1获取文件后缀名
            String extName = FileUtil.extName(file.getOriginalFilename());
            //2.2生成唯一文件名
            String filePath = "/" + folder + "/" + fileName + "." + extName;
            //2.3 上传文件
            minioClient.putObject(
                    PutObjectArgs.builder()
                            .bucket(properties.getBucketName())
                            .object(filePath)
                            .stream(file.getInputStream(),file.getSize(),-1)
                            .contentType(file.getContentType())
                            .build()
            );
            //3返回文件路径
            return properties.getEndpointUrl() + "/" + properties.getBucketName() + filePath;
        } catch (Exception e) {
            log.error("[专辑服务]文件上传失败：{}", e);
            throw new RuntimeException(e);
        }
    }
    public String upload(MultipartFile file) {
        try {

            //2.上传文件 /2024-9-29/UUid.jgp
            String folder = DateUtil.today();
            String fileName = IdUtil.randomUUID();
            //2.1获取文件后缀名
            String extName = FileUtil.extName(file.getOriginalFilename());
            //2.2生成唯一文件名
            String filePath = "/" + folder + "/" + fileName + "." + extName;
            //2.3 上传文件
            // 将 MultipartFile 转换为临时文件
            File tempFile = File.createTempFile("upload-", file.getOriginalFilename());
            file.transferTo(tempFile);

            minioClient.uploadObject(
                    UploadObjectArgs.builder()
                            .bucket(properties.getBucketName())
                            .object(filePath)
                            .filename(tempFile.getAbsolutePath())
                            .contentType(file.getContentType())
                            .build()
            );
            // 删除临时文件
            tempFile.delete();
            //3返回文件路径
            return properties.getEndpointUrl() + "/" + properties.getBucketName() + filePath;
        } catch (Exception e) {
            log.error("[专辑服务]文件上传失败：{}", e);
            throw new RuntimeException(e);
        }
    }
}
